package com.ponhu.ea2.support.validation.validator;

import com.ponhu.ea2.support.validation.annotions.ValidateEnumValue;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * 枚举校验注解处理类
 * @author Wang
 * @date 2021/10/20 5:23 下午
 */
public class EnumValueValidator implements ConstraintValidator<ValidateEnumValue, Object>  {

    private String[] strValues;
    private int[] intValues;
    private boolean required;

    @Override
    public void initialize(ValidateEnumValue constraintAnnotation) {
        strValues = constraintAnnotation.strValues();
        intValues = constraintAnnotation.intValues();
        required = constraintAnnotation.required();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
        if(value == null && !required){
            return true;
        }

        if (value instanceof String) {
            for (String s : strValues) {
                if (s.equals(value)) {
                    return true;
                }
            }
        } else if (value instanceof Integer) {
            for (int s : intValues) {
                if (s == ((Integer) value).intValue()) {
                    return true;
                }
            }
        }
        return false;
    }
}
